<template>
  <div class="coupon-list">
    <!-- 搜索区域 -->
    <el-card class="search-card">
      <el-form :model="formInline" inline>
        <el-form-item label="活动名称">
          <el-input v-model="formInline.name" placeholder="请输入活动名称" clearable />
        </el-form-item>

        <el-form-item label="活动状态" class="status-form-item">
          <el-select
            v-model="formInline.status"
            placeholder="请选择活动状态"
            clearable
            class="status-select"
          >
            <el-option label="报名未开始" value="0" />
            <el-option label="报名进行中" value="1" />
            <el-option label="活动待开始" value="2" />
            <el-option label="活动进行中" value="3" />
            <el-option label="活动已结束" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="search">查询</el-button>
          <el-button @click="clear">重置</el-button>
          <el-button type="success" @click="addCoupon">新建活动</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card class="table-card">
      <data-table
        :table-data="tableData"
        :loading="loading"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        @view="handleView"
        @edit="handleEdit"
        @end="handleEnd"
        @delete="handleDelete"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 新增/编辑弹窗 -->
    <coupon-add v-model="addVisible" :data="currentData" @success="handleAddSuccess" />

    <!-- 详情抽屉 -->
    <coupon-detail v-model="detailVisible" :data="currentData" />
  </div>
</template>

<script setup>
  import { ref, reactive, onMounted } from 'vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import DataTable from './component/dataTable.vue'
  import CouponAdd from './couponAdd.vue'
  import CouponDetail from './couponDetail.vue'
  import { getCouponData, delCoupon, endCoupon } from '@/api/active'

  // 搜索表单
  const formInline = reactive({
    name: '',
    status: ''
  })

  // 表格数据
  const tableData = ref([])
  const loading = ref(false)
  const total = ref(0)
  const currentPage = ref(1)
  const pageSize = ref(10)

  // 弹窗控制
  const addVisible = ref(false)
  const detailVisible = ref(false)

  // 当前操作的数据
  const currentData = ref({})

  // 获取数据
  const getAll = async () => {
    loading.value = true
    try {
      const params = {
        activityName: formInline.name,
        state: formInline.status,
        page: currentPage.value,
        pageSize: pageSize.value
      }
      console.log('准备发送请求')
      const response = await getCouponData(params)
      console.log('请求已发送....')
      console.log(response)

      if (response.code === '200') {
        console.log('获取数据成功')
        tableData.value = response.data.list
        total.value = response.data.total
      } else {
        console.log('获取数据失败2')
        ElMessage.error('获取数据失败: ' + response.message)
      }
    } catch (error) {
      console.log('我失败了')
      ElMessage.error('获取数据失败: ' + error.message)
    } finally {
      loading.value = false
    }
  }

  // 查询
  const search = () => {
    currentPage.value = 1
    getAll()
  }

  // 重置
  const clear = () => {
    formInline.name = ''
    formInline.status = ''
    currentPage.value = 1
    getAll()
  }

  // 新增优惠券
  const addCoupon = () => {
    currentData.value = {}
    addVisible.value = true
  }

  // 查看详情
  const handleView = (row) => {
    currentData.value = { ...row }
    detailVisible.value = true
  }

  // 编辑
  const handleEdit = (row) => {
    currentData.value = { ...row }
    addVisible.value = true
  }

  // 结束活动
  const handleEnd = (row) => {
    ElMessageBox.confirm(`确定要结束"${row.activityName}"活动吗？`, '结束确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const response = await endCoupon({ activityId: row.activityId })
          if (response.data.code === '200') {
            ElMessage.success('结束活动成功')
            getAll()
          } else {
            ElMessage.error('结束活动失败: ' + (response.data.message || '未知错误'))
          }
        } catch (error) {
          ElMessage.error('结束活动失败: ' + (error.message || '网络错误'))
        }
      })
      .catch(() => {
        // 取消结束
      })
  }

  // 删除
  const handleDelete = (row) => {
    ElMessageBox.confirm(`确定要删除"${row.activityName}"活动吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
      .then(async () => {
        try {
          const response = await delCoupon({ activityId: row.activityId })
          if (response.data.code === '200') {
            ElMessage.success('删除成功')
            getAll()
          } else {
            ElMessage.error('删除失败: ' + (response.data.message || '未知错误'))
          }
        } catch (error) {
          ElMessage.error('删除失败: ' + (error.message || '网络错误'))
        }
      })
      .catch(() => {
        // 取消删除
      })
  }

  // 新增/编辑成功
  const handleAddSuccess = () => {
    getAll()
  }

  // 分页相关
  const handleSizeChange = (val) => {
    pageSize.value = val
    currentPage.value = 1
    getAll()
  }

  const handleCurrentChange = (val) => {
    currentPage.value = val
    getAll()
  }

  // 初始化数据
  onMounted(() => {
    getAll()
  })
</script>

<style scoped>
  .coupon-list {
    padding: 20px;
  }

  .search-card {
    margin-bottom: 20px;
  }

  .table-card {
    margin-bottom: 20px;
  }

  .status-form-item {
    width: 250px;
  }

  .status-select {
    width: 100%;
  }
</style>
